from fcntl import flock, LOCK_UN, LOCK_EX, LOCK_NB
from os import path
from time import time
file_dir = path.dirname(__file__)

def lock(file):
	try:
		flock(file, LOCK_EX | LOCK_NB)
		return True
	except Exception as e:
		return False

def unlock(file):
	try:
		flock(file, LOCK_UN)
		return True
	except Exception as e:
		return False


def lock_retry(file, timeout=10):
	end = time() + timeout
	while time() <= end:
		if lock(file):
			return True
		else:
			return False

def unlock_retry(file, timeout=10):
	end = time() + timeout
	while time() <= end:
		if unlock(file):
			return True
		else:
			return False


class FileLockError(Exception):
    def __init__(self, type=str):
        self.type = type

    def __str__(self):
        return f"FileLockError: Encountered an error while {self.type}ing."



def main():
	with open(f'{file_dir}/file.txt', 'w') as file:
		if lock(file):
			file.write('Hello World!')
			if unlock(file):
				return True
			else:
				return False
		else:
			return False

if __name__ == '__main__':
	#print(main())
	raise FileLockError('lock')